//
//  SAMemberSetVC.m
//  saasRetail
//
//  Created by 黄志刚 on 2021/6/21.
//

#import "SAMemberSetVC.h"
#import "SAAddVipLevelVC.h"
#import "SAMemberSetCell.h"
#import "SASystemSettingsListAPI.h"
#import "SACommoditySpecialFeesModel.h"
#import "SAMemberIsupdateAPI.h"
#import "GFAlertView.h"
#import "SASystemSettingsCheckAPI.h"

@interface SAMemberSetVC ()<UITableViewDataSource, UITableViewDelegate, HTTPAPIDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray<SACommoditySpecialFeesModel *> *dataMarr;
@property (nonatomic, strong) SASystemSettingsListAPI *systemSettingsListAPI;
@property (nonatomic, strong) NSString *templateId;
@property (nonatomic, strong) SAMemberIsupdateAPI *memberIsupdateAPI;
@property (nonatomic, strong) NSString *settingsId;
@property (nonatomic, strong) SASystemSettingsCheckAPI *systemSettingsCheckAPI;

@end

@implementation SAMemberSetVC

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.systemSettingsListAPI sendRequestToServerWithActivityViewAndMask:GET];
}

- (void)viewDidLoad {
    [super viewDidLoad];
}

#pragma mark - HTTPAPIDelegate
- (void)fetchData:(id)data fromServerSuccessedWithAPI:(HTTPAPI *)api {
    if (self.systemSettingsListAPI == api) {
        self.templateId = data[@"data"][@"member_level_setting"][@"templateId"];
        self.dataMarr = [SACommoditySpecialFeesModel mj_objectArrayWithKeyValuesArray:data[@"data"][@"member_level_setting"][@"childSettings"]];
        for (int i = 0; i < self.dataMarr .count; i++) {
            for (int j = i+1; j < self.dataMarr.count; j++) {
                NSArray *arr1 = [self.dataMarr[i].value componentsSeparatedByString:@","];
                NSArray *arr2 = [self.dataMarr[j].value componentsSeparatedByString:@","];
                if (arr1.count > 1 && arr2.count > 1) {
                    double x = [arr1[2] doubleValue];
                    double y = [arr2[2] doubleValue];
                    if (x > y) {
                        [self.dataMarr exchangeObjectAtIndex:i withObjectAtIndex:j];
                    }
                }
            }
        }
        [self.tableView reloadData];
    }else if (self.memberIsupdateAPI == api) {
        GFAlertView *alertView = [GFAlertView alertViewWithMsg:@"提示" detailMsg:@"确认删除该会员级别?" knowBtnBlock:^(UIButton *knowBtn) {
            [knowBtn addTarget:self action:@selector(clickedDelete) forControlEvents:UIControlEventTouchUpInside];
        }];
        [alertView showWithAnimation];
    }else if (self.systemSettingsCheckAPI == api) {
        [self.systemSettingsListAPI sendRequestToServerWithActivityViewAndMask:GET];
    }
}

- (void)fetchDataFromServerFailedWithError:(NSError *)error API:(HTTPAPI *)api {
  
}

#pragma mark - UITableView Delegate & DataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataMarr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SAMemberSetCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SAMemberSetCell" forIndexPath:indexPath];
    cell.model = self.dataMarr[indexPath.section];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    SAAddVipLevelVC *pushVC = [[SAAddVipLevelVC alloc] initWithId:@"" AndParentId:@""];
    pushVC.model = self.dataMarr[indexPath.section];
    [self.navigationController pushViewController:pushVC animated:YES];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return kScaleNum(40);
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {

    return [[UIView alloc] initWithFrame:CGRectZero];
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc] initWithFrame:CGRectZero];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return kScaleNum(0.001);
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return kScaleNum(0.5);
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    SACommoditySpecialFeesModel *model = self.dataMarr[indexPath.section];
    NSArray *arr = [model.value componentsSeparatedByString:@","];
    if (arr.count > 0) {
        NSInteger i = [arr[0] integerValue];
        if (i == 0) {
            return NO;
        }
    }
    return YES;
}

-(NSArray<UITableViewRowAction*>*)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
    WeakSelf
    SACommoditySpecialFeesModel *model = self.dataMarr[indexPath.section];
    NSArray *valueArr = [model.value componentsSeparatedByString:@","];
    self.settingsId = model.settingsId;
    UITableViewRowAction *rowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault
                                                                         title:@"删除" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        if (valueArr.count > 1) {
            weakSelf.memberIsupdateAPI.memberLevel = valueArr[0];
            [weakSelf.memberIsupdateAPI sendRequestToServerWithActivityViewAndMask:GET];
        }
    }];
    rowAction.backgroundColor = kPinkColor;
    NSArray *arr = @[rowAction];
    return arr;
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{
    return @"删除";
}

#pragma mark - event
-(void)clickedAddBtn {
    NSInteger idStr = 0;
    for (SACommoditySpecialFeesModel *model in self.dataMarr) {
        NSArray *arr1 = [model.value componentsSeparatedByString:@","];
        if (arr1.count > 0) {
            NSInteger i = [arr1[0] integerValue];
            if (idStr < i) {
                idStr = i;
            }
        }
    }
    SAAddVipLevelVC *pushVC = [[SAAddVipLevelVC alloc] initWithId:[NSString stringWithFormat:@"%zd",idStr + 1] AndParentId:self.templateId];
    [self.navigationController pushViewController:pushVC animated:YES];
}

-(void)clickedDelete {
    self.systemSettingsCheckAPI.isDelete = @"1";
    self.systemSettingsCheckAPI.settingsId = self.settingsId;
    self.systemSettingsCheckAPI.parentId = self.templateId;
    [self.systemSettingsCheckAPI sendRequestToServerWithActivityViewAndMask:POST];
}

#pragma mark - initUI
-(void)initUI {
    
    [self setNavigationItemBackBBIAndTitle:@"会员级别"];
    [self setBgImage:nil];
    
    UIButton *addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    addBtn.frame = CGRectMake(0, 0, kScaleNum(60), kScaleNum(44));
    [addBtn setImage:[UIImage imageNamed:@"white_add"] forState:UIControlStateNormal];
    [addBtn addTarget:self action:@selector(clickedAddBtn) forControlEvents:UIControlEventTouchUpInside];
    [self addRightViews:@[addBtn]];
    
    UIView *grayView = [[UIView alloc] initWithFrame:CGRectMake(0, kScaleNum(StatusHeight), kScreenWidth, kScaleNum(30))];
    grayView.backgroundColor = kTextBgColor;
    [self.view addSubview:grayView];
    NSArray *arr2 = @[@"会员级别", @"折扣(%)", @"成长值(元)"];
    for (int i = 0; i < arr2.count; i++) {
        UILabel *titleLab = [[UILabel alloc] init];
        titleLab.text = arr2[i];
        titleLab.font = kFont(15);
        titleLab.textColor = kTextColor;
        [grayView addSubview:titleLab];
        titleLab.textAlignment = NSTextAlignmentCenter;
        if (i == 0) {
            titleLab.frame = CGRectMake(kScaleNum(30), 0, kScaleNum(105), kScaleNum(30));
        }else if (i == 1) {
            titleLab.frame = CGRectMake(kScaleNum(135), 0, kScaleNum(105), kScaleNum(30));
        }else if (i == 2) {
            titleLab.frame = CGRectMake(kScaleNum(240), 0, kScaleNum(105), kScaleNum(30));
        }
    }
    
    [self.view addSubview:self.tableView];
}


-(UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, kScaleNum(StatusHeight + 30), kScreenWidth, kScreenHeight - kScaleNum(StatusHeight + 30)) style:UITableViewStyleGrouped];
        _tableView.backgroundColor = kBgColor;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsHorizontalScrollIndicator = NO;
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        _tableView.bounces = NO;
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        [_tableView registerClass:[SAMemberSetCell class] forCellReuseIdentifier:@"SAMemberSetCell"];
    }
    return _tableView;
}

-(SASystemSettingsListAPI *)systemSettingsListAPI {
    if (!_systemSettingsListAPI) {
        _systemSettingsListAPI = [SASystemSettingsListAPI apiWithDelegate:self];
    }
    return _systemSettingsListAPI;
}

-(NSMutableArray<SACommoditySpecialFeesModel *> *)dataMarr {
    if (!_dataMarr) {
        _dataMarr = [NSMutableArray array];
    }
    return _dataMarr;
}

-(SAMemberIsupdateAPI *)memberIsupdateAPI {
    if (!_memberIsupdateAPI) {
        _memberIsupdateAPI = [SAMemberIsupdateAPI apiWithDelegate:self];
    }
    return _memberIsupdateAPI;
}

-(SASystemSettingsCheckAPI *)systemSettingsCheckAPI {
    if (!_systemSettingsCheckAPI) {
        _systemSettingsCheckAPI = [SASystemSettingsCheckAPI apiWithDelegate:self];
    }
    return _systemSettingsCheckAPI;
}

@end
